<template>
  <div style="padding: 20px">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <span>个人信息</span>
          </template>
          <div style="text-align: center;">
            <el-avatar :size="100" :src="avatar"/>
            <el-divider class="divider-margin"/>
            <el-form label-width="100">
              <el-form-item class="form-item-height">
              <template #label>
                <el-icon size="16" style="line-height: 32px;height: 32px"><User /></el-icon>
                <span>用户名称</span>
              </template>
                {{ userInfo.userName }}
              </el-form-item>
              <el-divider class="divider-margin"/>
              <el-form-item class="form-item-height">
                <template #label>
                  <el-icon size="16" style="line-height: 32px;height: 32px"><UserFilled /></el-icon>
                  <span>真实姓名</span>
                </template>
                {{ userInfo.realName }}
              </el-form-item>
              <el-divider class="divider-margin"/>
              <el-form-item class="form-item-height">
                <template #label>
                  <el-icon size="16" style="line-height: 32px;height: 32px"><Postcard /></el-icon>
                  <span>用户工号</span>
                </template>
                {{ userInfo.stuId }}
              </el-form-item>
              <el-divider class="divider-margin"/>
              <el-form-item class="form-item-height">
                <template #label>
                  <el-icon size="16" style="line-height: 32px;height: 32px"><Iphone /></el-icon>
                  <span>手机电话</span>
                </template>
                {{ userInfo.telephone }}
              </el-form-item>
              <el-divider class="divider-margin"/>
              <el-form-item class="form-item-height">
                <template #label>
                  <el-icon size="16" style="line-height: 32px;height: 32px"><Promotion/></el-icon>
                  <span>用户邮箱</span>
                </template>
                {{ userInfo.email }}
              </el-form-item>
              <el-divider class="divider-margin"/>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <template #header>
            <span>基本资料</span>
          </template>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="userInfo">
              <el-form label-position="right" label-width="100" :model="userForm" :rules="rules">
                <el-form-item prop="realName">
                  <template #label>
                    <span class="font-bold">真实姓名</span>
                  </template>
                  <el-input size="large" v-model="userForm.realName" />
                </el-form-item>
                <el-form-item prop="stuId">
                  <template #label>
                    <span class="font-bold">用户工号</span>
                  </template>
                  <el-input size="large" v-model="userForm.stuId"/>
                </el-form-item>
                <el-form-item prop="email">
                  <template #label>
                    <span class="font-bold">用户邮箱</span>
                  </template>
                  <el-input size="large" v-model="userForm.email"/>
                </el-form-item>
                <el-form-item prop="telephone">
                  <template #label>
                    <span class="font-bold">手机电话</span>
                  </template>
                  <el-input size="large" v-model="userForm.telephone" />
                </el-form-item>
                <el-form-item>
                  <el-button
                      type="primary"
                      @click="submitUser(userForm)"
                  >保存</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="changePwd">
              <el-form :model="changePwdForm"
                       :rules="changeRules"
                       v-if="!isChangePwd"
                       ref="changePwdFormRef"
                       autocomplete="off"
                       label-position="right"
                       label-width="80">
                <el-form-item label="旧 密 码" prop="oldPassword">
                  <el-input v-model="changePwdForm.oldPassword" show-password autocomplete="new-password"
                            placeholder="请输入旧密码" style="height: 36px"></el-input>
                </el-form-item>

                <el-form-item label="新 密 码" prop="newPassword">
                  <el-input v-model="changePwdForm.newPassword" show-password autocomplete="new-password"
                            placeholder="请输入新密码" style="height: 36px"></el-input>
                </el-form-item>

                <el-form-item  label="确认密码" prop="confirmPassword" :error="errMsg" >
                  <el-input v-model="changePwdForm.confirmPassword" show-password autocomplete="new-password"
                            placeholder="请再次输入密码确认" style="height: 36px"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button class="login-button" type="primary" @click="handleChangePwd(changePwdFormRef)">
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
              <el-result
                  icon="success"
                  title="重置修改成功"
                  sub-title="Password change successful"
                  v-else
              >
                <template #extra>
                  <el-button type="primary" @click="goToLogin">重新登录</el-button>
                </template>
              </el-result>
            </el-tab-pane>
            <el-tab-pane label="重置密码" name="resetPwd">
              <el-form
                  :model="resetForm"
                  :rules="rules"
                  ref="ruleFormRef"
                  style="overflow:hidden;"
                  autocomplete="off"
                  label-position="right"
                  label-width="80"
                  v-if="!isReset"
              >
                <el-form-item label="用户邮箱" prop="email">
                  <el-input v-model="resetForm.email" disabled placeholder="请输入您注册时的邮箱" style="height: 36px"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <el-input v-model="resetForm.code" placeholder="请输入邮箱验证码" style="height: 36px">
                    <template #append>
                      <el-button @click="handleSendCode(resetForm.email)" :disabled="sms.disabled || resetForm.email == null">
                        <span v-if="!sms.disabled">发送邮箱验证码</span>
                        <span v-else>{{ sms.count }}s后重新发送</span>
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="新 密 码" prop="password">
                  <el-input v-model="resetForm.password" show-password autocomplete="new-password"
                            placeholder="请输入新密码" style="height: 36px"></el-input>
                </el-form-item>

                <el-form-item  label="确认密码" prop="confirmPassword" :error="errMsg" >
                  <el-input v-model="resetForm.confirmPassword" show-password autocomplete="new-password"
                            placeholder="请再次输入密码确认" style="height: 36px"></el-input>
                </el-form-item>

                <el-form-item  label-width="10">
                  <el-button class="login-button" type="primary" @click="handleReset(ruleFormRef)">重置密码</el-button>
                </el-form-item>
              </el-form>
              <el-result
                  icon="success"
                  title="重置密码成功"
                  sub-title="Password reset successful"
                  v-else
              >
                <template #extra>
                  <el-button type="primary" @click="goToLogin">重新登录</el-button>
                </template>
              </el-result>

            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>

<!--  -->
<!--  <div class="user-box">-->
<!--      &lt;!&ndash;头像&ndash;&gt;-->
<!--      <div style="width: 30px;height: 30px; margin: auto;">-->
<!--        <img src="../../assets/avatar.jpg" alt="" style="width: 70px;height: 70px;border-radius: 50%">-->
<!--      </div>-->
<!--      -->
<!--  </div>-->
</template>

<script setup>
import { ref , onMounted , reactive } from "vue";
import {getUserInfo, updateUser, changePassword} from "@/api/userInfo"
import {ElMessage} from "element-plus";
import {Female, Promotion, User} from "@element-plus/icons-vue";
import {checkUserEmail, checkUsername, resetPassword, sendEmailCode} from "@/api/reset.js";
import {logout} from "@/api/login.js";
import router from "@/routers/index.js";
import avatar from '@/assets/avatar.jpg'

const img = ref('')
const inputCan = ref(true)
const activeTab = ref('userInfo')
const userInfo = reactive(defaultValue())
const userForm = reactive(defaultValue())
function defaultValue(){
  return {
    email: null,
    realName: null,
    stuId: null,
    telephone: null,
    userId: null,
    userName: null
  }
}
const isChangePwd = ref(false)
const changePwdFormRef = ref()
const changePwdForm = reactive({
  oldPassword: null,
  newPassword: null,
  confirmPassword: null
})

const changeRules = {
  oldPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  newPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  confirmPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {validator: checkChangePassword, message: '两次密码不一致', trigger: 'blur'}
  ],
}

const sms = reactive({
  disabled: false,
  total: 60,
  count: 0
})
const errMsg = ref('')
const isReset = ref(false)
const ruleFormRef = ref()
const isEmailOk = ref(false)
const resetForm = reactive({
  username: null,
  password: null,
  confirmPassword: null,
  email: null,
  code: null,
  uuid: null,
})
const rules = {
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  realName: [
    {required: true, message: '真实姓名不能为空', trigger: 'blur'},
  ],
  telephone: [
    {required: true, message: '电话不能为空', trigger: 'blur'},
  ],
  stuId: [
    {required: true, message: '工号不能为空', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确的邮箱'}
  ],
  oldPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  newPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  confirmPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {validator: checkResetPassword, message: '两次密码不一致', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
    {pattern: /^[0-9A-Za-z]{6}$/, message: '请输入正确格式的验证码'}
  ]
}


onMounted(async () =>{
  init()
})

function init(){
  getUserInfo().then(res =>{
    Object.assign(userInfo,res.data)
    Object.assign(userForm,res.data)
    resetForm.email = res.data.email
    window.localStorage.setItem("miaomiao-userInfo",JSON.stringify(res.data))
  })
}

function cancel() {
    inputCan.value = true;
    // userInfo = JSON.parse(localStorage.getItem("login"));
  }
function submitUser(data) {
  console.log(data)
  updateUser(data).then(res => {
    init()
    ElMessage.success(res.msg);
  }).catch((err) => {
    console.log(err)
    ElMessage.error("更改失败")
  })
}

const timerHandler = () => {
  sms.count = sms.total
  sms.disabled = true

  let timer = setInterval(() => {
    if (sms.count > 1 && sms.count <= sms.total) {
      sms.count--
    } else {
      sms.disabled = false
      clearInterval(timer)
    }
  }, 1000)
}

async function checkUserName(){
  let flag = false;
  await checkUsername(resetForm.username).then(res =>{
    flag = res.code == 200
  })
  return flag
}
async function checkEmail(){
  let flag = false;
  isEmailOk.value = false
  await checkUserEmail(resetForm.username,resetForm.email).then(res =>{
    if(res.code == 200) {
      flag = true
      isEmailOk.value = true
    }
  })
  return flag
}

function checkResetPassword(){
  return resetForm.password == resetForm.confirmPassword
}

function checkChangePassword(){
  return changePwdForm.newPassword == changePwdForm.confirmPassword
}
function handleReset(formEl){
  if (!formEl) return
  formEl.validate((valid) =>{
    if(valid){
      resetPassword(resetForm).then(res =>{
        if(res.code == 200){
          handleLogout()
          isReset.value = true
        }
      })
    }else{
      ElMessage.error("请正确填写重置密码信息")
    }
  })
}

function handleSendCode(email){
  if(!isEmailOk){
    ElMessage.error("邮箱与该用户注册时的邮箱不一致！")
  }
  const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
  if(reg.test(email)){
    sendEmailCode(email).then(res =>{
      resetForm.uuid = res.data.uuid
    })
    timerHandler()
  }else{
    ElMessage.error("邮箱格式不正确")
  }
}
function handleLogout(){
  logout().then(res => {
    window.localStorage.removeItem('token')
    window.localStorage.removeItem("miaomiao-userInfo")
    ElMessage.warning("密码已修改，请重新登录！")
  })
}
function goToLogin(){
  router.push({path:'/login'})
}
function handleChangePwd(formEl){
  if (!formEl) return
  formEl.validate((valid) =>{
    if(valid){
      changePassword(changePwdForm).then(res =>{
        if(res.code == 200){
          handleLogout()
          isChangePwd.value = true
        }
      })
    }else{
      ElMessage.error("请正确填写修改密码信息")
    }
  })
}
</script>

<style>
.font-bold{
  font-weight: bold;
}
.divider-margin{
  margin: 10px 0;
}
.form-item-height{
  height: 16px;
}
</style>

